<template>
    <view class="luck-draw-main" :style="{ background: bgUrl }">
        <view @click="showRule = true" class="luck-rule">抽奖规则</view>
        <view @click="goToRecord" class="winning-record">中奖记录</view>
        <!-- 九宫格 -->
        <NineGrid
            v-if="Data.styleType == 1"
            ref="nineGridRef"
            :isLogin="isLogin"
            :drawStatus="Data.drawStatus"
            :drawNum="Data.drawNum"
            :activityInfo="Data.activityInfo"
            :hornData="Data.hornData"
            @startLuck="handlerActivityRotaryDraw"
            @endLuck="handlerEndLuck" />
        <!-- 大转盘 -->
        <Turntable
            v-if="Data.styleType == 2"
            ref="turntableRef"
            :isLogin="isLogin"
            :drawStatus="Data.drawStatus"
            :drawNum="Data.drawNum"
            :activityInfo="Data.activityInfo"
            :hornData="Data.hornData"
            @startLuck="handlerActivityRotaryDraw"
            @endLuck="handlerEndLuck" />
        <!-- 邀请好友抽奖 -->
        <view
            v-if="Data.activityInfo?.luckDrawConfig?.extraRaffleNum"
            :style="{ background: bgShare }"
            class="share-bg">
            <view class="share-container">
                <view class="share-left">
                    <view class="img-container">
                        <image class="img" :src="getImgOssUrl('/ui-prod-2.4.0/luck-share-person@2x.png')"></image>
                    </view>
                    <view class="text">
                        <view class="text-top"
                            >邀请新用户，得抽奖机会（{{ Data.drawDayNum }}/{{
                                Data.activityInfo.luckDrawConfig.extraRaffleNum
                            }}）</view
                        >
                        <view class="text-bottom">邀请1名新用户，抽奖机会+1</view>
                    </view>
                </view>
                <view
                    v-if="
                        Data.drawStatus === 0 ||
                        Data.drawStatus === 2 ||
                        Data.drawDayNum === Data.activityInfo.luckDrawConfig.extraRaffleNum
                    "
                    @click="noCanShare"
                    class="share-right no-share"
                    >去邀请</view
                >
                <view v-else-if="!isLogin" @click="noCanShare" class="share-right no-login">去邀请</view>
                <button v-else open-type="share" class="share-right">去邀请</button>
            </view>
        </view>
        <!-- 抽奖规则 -->
        <view v-if="showRule" @click="showRule = false" class="rule-container-bg">
            <view class="rule-container">
                <view class="title">抽奖规则</view>
                <view class="rule-detail">
                    <view
                        >活动时间：<text class="red"
                            >{{ Data.activityInfo.baseInfo.activityStartTime }}至{{
                                Data.activityInfo.baseInfo.endTime || Data.activityInfo.baseInfo.activityEndTime
                            }}</text
                        ></view
                    >
                    <view
                        >抽奖次数：每人每天可抽奖<text class="red">{{
                            Data.activityInfo.luckDrawConfig.everyDayNum
                        }}</text
                        >次；<text v-if="Data.activityInfo.luckDrawConfig.perPersonNum"
                            >每人一共可抽奖<text class="red"
                                >{{ Data.activityInfo.luckDrawConfig.perPersonNum }}次。</text
                            ></text
                        ><view v-if="Data.activityInfo.baseInfo.remark"
                            >{{ Data.activityInfo.baseInfo.remark }}。</view
                        ></view
                    >
                </view>
            </view>
        </view>
        <!-- 抽奖结果 -->
        <view v-if="showWinningRes" class="winning-result">
            <view :style="{ background: winningResImg }" class="res-container">
                <view class="title">{{ Data.winningRes[Data.isWinning ? 'isWinning' : 'isFail'].title }}</view>
                <image
                    :src="Data.winningRes[Data.isWinning ? 'isWinning' : 'isFail'].img"
                    :class="['img', Data.isWinning ? 'winning-img' : 'fail-img']" />
                <view class="text">{{ Data.winningRes[Data.isWinning ? 'isWinning' : 'isFail'].text }}</view>
                <view class="sub-text">{{ Data.winningRes[Data.isWinning ? 'isWinning' : 'isFail'].subText }}</view>
                <view v-if="Data.isWinning" class="winning-result-btn">
                    <view v-if="Data.hasRealPrize" @click="goToRecord">查看中奖记录</view>
                    <view v-else @click="goToCoupon">查看奖品</view>
                </view>
                <view v-else :class="['winning-result-btn', false ? '' : 'result-close-btn']">
                    <view v-if="Data.hasLuckNum" @click="againLuck">再抽一次</view>
                    <view v-else @click="showWinningRes = false">下次再来</view>
                </view>
                <view @click="showWinningRes = false" class="winning-result-close">
                    <image class="result-close-img" :src="getImgOssUrl('/ui-prod-2.4.0/pop-up-close@2x.png')" />
                </view>
            </view>
        </view>
    </view>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
import { onShareAppMessage, onShow } from '@dcloudio/uni-app';
import router from '@/router';
import { debounce } from 'lodash';
import { getImgOssUrl, checkToken, timeDiff } from '@/commons/utils';
import storage from '@/commons/storage';
import request from '@/request';
import NineGrid from '@/components/luckDraw/nineGrid.vue';
import Turntable from '@/components/luckDraw/turntable.vue';
import { getParamsBySceneHook } from '@/hooks';

const props = defineProps({
    /**活动id */
    luckDrawId: {
        default: '',
        type: [Number, String]
    },
    /**邀请人id ---> userId */
    inviteMemberId: {
        default: '',
        type: [Number, String]
    },
    // 门店id
    shopId: {
        default: '',
        type: [Number, String]
    },
    scene: {
        type: [String]
    }
});

const luckDrawIdArg = ref(0);

const bgUrl = computed(() => {
    if (Data.styleType == 1) {
        return ref(`url(${getImgOssUrl('/ui-prod-2.4.0/luck-page-bg@2x.png')})`);
    } else if (Data.styleType == 2) {
        return ref(`url(${getImgOssUrl('/ui-prod-2.5.0/luck-turntable-page-bg.png')})`);
    } else {
        return '';
    }
});
const bgShare = computed(() => {
    if (Data.styleType == 1) {
        return ref(`url(${getImgOssUrl('/ui-prod-2.4.0/luck-share-bg@2x.png')})`);
    } else if (Data.styleType == 2) {
        return ref(`url(${getImgOssUrl('/ui-prod-2.5.0/luck-turntable-share-bg.png')})`);
    } else {
        return '';
    }
});
const winningResImg = ref(`url(${getImgOssUrl('/ui-prod-2.4.0/pop-up-bg.png')})`);

const nineGridRef = ref(null);
const turntableRef = ref(null);

const showRule = ref(false);
const showWinningRes = ref(false);
const isLogin = ref(false);
const Data = reactive({
    styleType: 0, // 抽奖模式：1-九宫格，2-大转盘
    amplification_index: 0, //轮盘的当前滚动位置
    roll_flag: true, //是否允许滚动
    max_number: 8, //轮盘的全部数量
    speed: 300, //速度，速度值越大，则越慢 初始化为300
    myInterval: '', //定时器
    max_speed: 40, //滚盘的最大速度
    minturns: 8, //最小的圈数为2
    runs_now: 0, //当前已跑步数
    luck_num: 0, // 中奖位置！！！！！！！！！！！！！！！！！！！！！！！！！
    end_amp: 0, //上一次滚动的位置
    start_flag: true,
    isLucking: false, // 是否正在抽奖中
    freeNumber: 0,
    activityInfo: {}, // 活动信息
    hornData: [], // 顶部喇叭信息
    winPrizeMes: {}, // 中奖信息信息
    isWinning: true, // 是否中奖
    drawNum: 0, // 抽奖剩余次数
    drawDayNum: 0, // 邀请好友获得次数
    drawStatus: 0, // 抽奖状态：0 未开始 1 进行中 2 已结束
    hasLuckNum: false,
    hasRealPrize: false,
    winningRes: {
        isWinning: {
            title: '恭喜您，中奖了！',
            img: '',
            text: '',
            subText: ''
        },
        isFail: {
            title: '很遗憾，您没中奖！',
            img: '',
            text: '',
            subText: '谢谢参与'
        }
    }
});

const handlerActivityRotaryDraw = debounce(async () => {
    if (!isLogin.value) {
        router.push({
            path: '/pages-user/login/index',
            query: {
                luckDrawId: luckDrawIdArg.value,
                inviteMemberId: props.inviteMemberId,
                channel: 1
            }
        });
        return;
    }
    if (Data.isLucking) {
        return;
    }
    const { drawStatus, drawNum } = Data;
    if (drawNum === 0 || drawStatus === 0 || drawStatus === 2) {
        const title =
            drawStatus === 0 ? '抽奖活动还没开始~' : drawStatus === 2 ? '抽奖活动已结束~' : '今日抽奖机会已用完';
        uni.showToast({
            title,
            icon: 'none'
        });
        return;
    }
    if (!Data.start_flag) {
        return;
    }
    // roll点
    const res = await request('luckDrawServ', { id: luckDrawIdArg.value });
    Data.isLucking = true;
    Data.drawNum = Data.drawNum - 1;
    const index = Data.activityInfo.luckDrawTurntable.findIndex((item, index) => {
        if (res.data.luckDrawTurntable === 0) {
            return item.isDefault === 2;
        } else {
            return item.id === res.data.luckDrawTurntable;
        }
    });
    Data.winPrizeMes = Data.activityInfo.luckDrawTurntable[index];
    if (Data.start_flag == true) {
        Data.start_flag = false;
        if (Data.styleType == 1) {
            nineGridRef.value.startRolling(index);
        } else if (Data.styleType == 2) {
            turntableRef.value.startRolling(index);
        }
    }
}, 400);

const handlerEndLuck = () => {
    Data.isLucking = false;
    Data.start_flag = true;
    const { isDefault, awardType, awardName, awardImg } = Data.winPrizeMes;
    if (isDefault === 1) {
        Data.isWinning = true;
        Data.hasRealPrize = awardType === 1;
        Data.winningRes.isWinning.text = awardName;
        Data.winningRes.isWinning.subText = awardType === 2 ? '已自动发放至您的优惠券账户' : '';
        Data.winningRes.isWinning.img =
            awardImg && awardImg !== 'default' ? awardImg : getImgOssUrl('/ui-prod-2.4.0/pop-up-smile.png');
        awardImg;
    } else {
        Data.isWinning = false;
        Data.hasLuckNum = Data.drawNum !== 0;
        Data.winningRes.isFail.img =
            awardImg && awardImg !== 'default' ? awardImg : getImgOssUrl('/ui-prod-2.4.0/pop-up-smile.png');
    }
    setTimeout(() => {
        showWinningRes.value = true;
    }, 500);
};

const againLuck = () => {
    showWinningRes.value = false;
    handlerActivityRotaryDraw();
};
const getHornInfo = async () => {
    const res = await request('luckDrawHornServ', { id: luckDrawIdArg.value });
    Data.hornData = res.data;
};
const getRemainderNum = async () => {
    const res = await request('luckDrawNumServ', { id: luckDrawIdArg.value });
    const { drawDayNum, drawNum } = res.data;
    Data.drawNum = drawNum;
    Data.drawDayNum = drawDayNum;
};
const getActivityInfo = async () => {
    const res = await request('luckDrawInfoServ', { id: luckDrawIdArg.value });
    Data.activityInfo = res.data;
    const { activityStartTime, activityEndTime, endTime } = Data.activityInfo.baseInfo;
    Data.styleType = Data.activityInfo.luckDrawConfig.styleType;
    if (!timeDiff(activityStartTime)) {
        Data.drawStatus = 0;
    } else if (endTime || timeDiff(activityEndTime)) {
        Data.drawStatus = 2;
    } else {
        Data.drawStatus = 1;
    }
    if (Data.styleType == 1) {
        // 九宫格-中间特殊处理
        Data.activityInfo.luckDrawTurntable.splice(4, 0, { key: 'draw', awardName: '抽奖' });
    }
    const activeIndexList = [1, 2, 3, 8, -1, 4, 7, 6, 5];
    Data.activityInfo.luckDrawTurntable.forEach((item, index) => {
        Data.activityInfo.luckDrawAward.forEach((subItem, subIndex) => {
            if (item.awardRelation === subItem.awardRelation) {
                Data.activityInfo.luckDrawTurntable[index] = Object.assign(
                    Data.activityInfo.luckDrawTurntable[index],
                    Data.activityInfo.luckDrawAward[subIndex]
                );
            }
            if (Data.styleType == 1) {
                Data.activityInfo.luckDrawTurntable[index].active_index = activeIndexList[index];
            }
        });
    });
};
const goToRecord = () => {
    showWinningRes.value = false;
    router.push({
        path: '/pages-cart/winningRecord/index'
    });
};
const goToCoupon = () => {
    showWinningRes.value = false;
    router.push('/pages-user/coupon/list/index');
};
const noCanShare = () => {
    if (!isLogin.value) {
        router.push('/pages-user/login/index');
        return;
    }
    const { drawStatus, drawNum } = Data;
    const title =
        drawStatus === 0 ? '抽奖活动还没开始~' : drawStatus === 2 ? '抽奖活动已结束~' : '额外的抽奖次数已达上限';
    uni.showToast({
        title,
        icon: 'none'
    });
};
onShow(async () => {
    if (props.scene) {
        const res = await getParamsBySceneHook(props.scene);
        luckDrawIdArg.value = res.luckDrawId;
        // storage.set('ZW_SHOP_ID', Number(res.shopId));
    } else {
        luckDrawIdArg.value = props.luckDrawId;
        // props.shopId && storage.set('ZW_SHOP_ID', Number(props.shopId));
    }

    isLogin.value = await checkToken();
    await getActivityInfo();
    if (isLogin.value) {
        await getRemainderNum();
    }
    getHornInfo();
});
onShareAppMessage(res => {
    const { shareCopy, shareImg } = Data.activityInfo.luckDrawConfig;
    const userId = storage.get('userId');
    const isDefaultImg = getImgOssUrl('/ui-prod-2.4.0/share-default.png');
    const shopId = uni.getStorageSync('ZW_SHOP_ID') || '';
    return {
        title: shareCopy,
        path: `/pages-cart/luckDraw/index?inviteMemberId=${userId}&luckDrawId=${luckDrawIdArg.value}&shopId=${shopId}`,
        imageUrl: shareImg && shareImg !== 'default' ? shareImg : isDefaultImg
    };
});
</script>
<style lang="scss" scoped src="./index.scss"></style>
